; CyUku/src/tools/runner.asm
; 代码运行器实现

section .text
global _start

_start:
    ; 检查参数
    cmp rdi, 2
    jl .usage
    
    ; 打开文件
    mov rax, SYS_OPEN
    mov rdi, [rsi + 8]  ; 文件名
    mov rsi, O_RDONLY
    syscall
    test rax, rax
    js .error
    
    ; 读取文件
    mov rdi, rax
    mov rax, SYS_READ
    mov rsi, buffer
    mov rdx, BUFFER_SIZE
    syscall
    
    ; 关闭文件
    mov rax, SYS_CLOSE
    syscall
    
    ; 初始化虚拟机
    call init_vm
    
    ; 执行字节码
    mov rdi, buffer
    mov rsi, rax  ; 文件大小
    call execute_bytecode
    
    ; 退出
    mov rax, SYS_EXIT
    xor rdi, rdi
    syscall

.usage:
    ; 显示用法信息
    mov rax, SYS_WRITE
    mov rdi, STDERR
    mov rsi, usage_msg
    mov rdx, usage_len
    syscall
    jmp .exit

.error:
    ; 错误处理
    mov rax, SYS_WRITE
    mov rdi, STDERR
    mov rsi, error_msg
    mov rdx, error_len
    syscall

.exit:
    mov rax, SYS_EXIT
    mov rdi, 1
    syscall

section .data
    buffer times 4096 db 0
    BUFFER_SIZE equ $ - buffer
    usage_msg db "Usage: runner <file.cuk>", 10
    usage_len equ $ - usage_msg
    error_msg db "Error executing program", 10
    error_len equ $ - error_msg
    SYS_OPEN equ 2
    SYS_READ equ 0
    SYS_CLOSE equ 3
    SYS_EXIT equ 60
    SYS_WRITE equ 1
    STDERR equ 2
    O_RDONLY equ 0